<template>
  <div class="warpper-box ensureOrder">
    <enterprise-select v-if="userInfo.type == 4" ref="enterprise"
      @enterpriseChange="enterpriseChange"></enterprise-select>
    <a-card style="margin-top: 10px;">
      <a-form layout="inline">
        <a-form-item label="月份选择">
          <a-month-picker valueFormat="YYYY-MM" placeholder="选择月份" v-model="params.refundMonth"></a-month-picker>
        </a-form-item>
        <a-form-item label="结算状态">
          <a-select v-model="params.refundBillStatus" placeholder="选择结算状态" style="width: 160px;">
            <a-select-option key="1">待提交</a-select-option>
            <a-select-option key="2">待支付</a-select-option>
            <a-select-option key="3">已支付</a-select-option>
            <a-select-option key="4">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="search" @click="loadTable(true)">搜索</a-button>
          <a-button type="primary" icon="setting" @click="reset()">重置</a-button>
          <a-button type="primary" @click="$refs.createInfo.add(true, enterpriseId)">发起退缴</a-button>
          <a-button type="primary" @click="importHandle">批量导入退缴</a-button>
          <a-button type="primary" @click="downloadOrderBill">导出</a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
        @change="handleTableChange" rowKey="insureRefundBillId" style="margin-top: 10px;">
        <!-- 操作栏-->
        <span slot="action" slot-scope="text, record">
          <!-- 编辑模块 | 字段 -->
          <span v-if="record.refundBillStatus == 1">
            <a-popconfirm title="确认提交?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 2)">
              <a>提交</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm title="确认撤销?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 0)">
              <a>撤销</a>
            </a-popconfirm>
            <a-divider type="vertical" />
          </span>
          <span v-else-if="record.refundBillStatus == 2">
            <a-popconfirm title="确认支付?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 3)">
              <a>支付</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm title="确认拒绝?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 4)">
              <a>拒绝</a>
            </a-popconfirm>
            <a-divider type="vertical" />
          </span>
          <a @click="$refs.createInfo.add(record, enterpriseId)">详情</a>
        </span>
      </a-table>
    </a-card>
    <add-info ref="createInfo" @on-ok="addLoad"></add-info>
    <!-- 批量导入退缴 -->
    <a-modal v-model="importVisible" title="导入详情" width="540px" :footer="null">
      <a-space style="margin-bottom: 10px;">
        退缴服务商选择
        <a-select placeholder="请选择" v-model="parkId" style="width: 185px;">
          <a-select-option v-for="item in parkList" :key="item.parkId">{{ item.parkName }}</a-select-option>
        </a-select>
      </a-space>
      <a-alert message="第一步：下载导入信息模板；模版内的表头请勿改动，防止导入时出错。" type="info" />
      <a-button type="primary" @click="downloadOrder" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入数据；请填写完整的信息。" type="info" />
      <a-button type="primary" @click="importOrder" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileExcel"
        @change="importOrderHandle" style="display: none;" />
    </a-modal>
  </div>
</template>

<script>
import store from '@/store'
import EnterpriseSelect from "@/components/human/enterpriseSelect.vue"
import {
  COLUMNS_ENSUREORDERRETURN
} from "./form"
import AddInfo from "./ensureOrderReturn_add.vue"
import {
  getTableReturnPage,
  refundBillOperate,
  exportInsureRefundBill,
  exportInsureRefundBillTemplateExcel,
  importInsureRefundBillFile
} from "@/api/human/ensureEnsureOrder"
import {
  parkRelation
} from "@/api/human/ensurePayOrder"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'ensureOrderReturn',
  components: {
    AddInfo,
    EnterpriseSelect
  },
  data() {
    return {
      params: {
        refundBillStatus: undefined,
        refundMonth: '',
      },
      table: {
        columns: COLUMNS_ENSUREORDERRETURN,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      enterpriseId: "", // 企业id
      enterpriseData: [], // 客户列表
      parkId: undefined, // 服务商id
      parkList: [], // 服务商列表
      importVisible: false,

      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据
    }
  },
  filters: {

  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
    if (this.userInfo.type == 4) {
      this.$refs.enterprise.getEnterpriseData();
    } else {
      this.enterpriseId = this.userInfo.relationId
      this.loadTable(true);
    }
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  methods: {
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取列表
    async loadTable(flag) {
      let params = this.params;
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.enterpriseId = this.enterpriseId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTableReturnPage(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 导出订单
    downloadOrderBill() {
      exportInsureRefundBill({
        enterpriseId: this.enterpriseId,
        refundBillStatus: this.params.refundBillStatus,
        refundMonth: this.params.refundMonth
      }).then(res => {
        const blob = new Blob([res]);
        const fileName = '社保退缴账单.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 获取服务商列表
    async getParkRelation() {
      const { code, data } = await parkRelation(this.enterpriseId);
      if (code == "1") {
        this.parkList = data;
      }
    },
    // 批量导入按钮
    importHandle() {
      this.importVisible = true;
      this.getParkRelation();
    },
    // 下载模板
    downloadOrder() {
      exportInsureRefundBillTemplateExcel().then(res => {
        const blob = new Blob([res]);
        const fileName = '社保退缴账单模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入表单
    importOrder() {
      if(this.parkId) {
        this.$refs.fileExcel.click();
      } else {
        this.$message.warning('请选择服务商');
      }
    },
    importOrderHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("parkId", _this.parkId);
        formData.append("file", file);
        importInsureRefundBillFile(formData).then((res) => {
          if (res.code == 1) {
            _this.importVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
          }
        })
      }
    },
    // 支付|拒绝|提交|撤销
    async operate(row, type) {
      let params = {
        insureRefundBillId: row.insureRefundBillId,
        optType: type
      }
      const { code } = await refundBillOperate(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 企业选择回调
    enterpriseChange(value) {
      this.enterpriseId = value;
      this.loadTable(true);
    },
    addLoad() {
      this.loadTable(true);
    },
    reset() {
      this.params.refundMonth = '';
      this.params.refundBillStatus = undefined;
      this.loadTable(true);
    }
  }
}
</script>
<style lang="less">
.ensureOrder {
  .ant-tabs-bar {
    margin-bottom: 5px;
  }
}
</style>